from aliyunsdkcore.acs_exception.exceptions import ServerException
from aliyunsdkcore.acs_exception.exceptions import ClientException
from Utils import Utils
import time
import argparse
from aliyunsdkalidns.request.v20150109.UpdateDomainRecordRequest import UpdateDomainRecordRequest

def DDNS(use_v6):
    client = Utils().getAcsClient()
    recordId = Utils().getRecordId(Utils().getConfigJson().get('Second-level-domain'))
    # print(recordId)
    if use_v6:
        ip = Utils().getRealIPv6()
        type = 'AAAA'
    else:
        ip = Utils().getRealIP()
        # print(ip)
        type = 'A'
    # print({'type': type, 'ip':ip})

    request = UpdateDomainRecordRequest()
    request.set_accept_format('json')

    # print(recordId,Utils().getConfigJson().get('Second-level-domain'),type,ip)
    request.set_TTL(600)
    request.set_RecordId(recordId)
    request.set_RR(Utils().getConfigJson().get('Second-level-domain'))
    request.set_Type(type)
    request.set_Value(ip)
    response = client.do_action_with_exception(request)
    return response

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='DDNS')
    parser.add_argument('-6', '--ipv6', nargs='*', default=False)
    args = parser.parse_args()
    isipv6 = isinstance(args.ipv6, list)
    # print(isipv6)

    try:
        while not Utils().isOnline:
            time.sleep(3)
            continue
        result = DDNS(isipv6)
        print("成功！")
    except (ServerException,ClientException) as reason:
        print("失败！原因为")
        print(reason.get_error_msg())

